package com.niu.crm.web.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.niu.crm.core.ResponseObject;
import com.niu.crm.core.error.BizException;
import com.niu.crm.core.error.GlobalErrorCode;
import com.niu.crm.form.StudentExportForm;
import com.niu.crm.form.StudentSearchForm;
import com.niu.crm.model.Exam;
import com.niu.crm.model.StuParent;
import com.niu.crm.model.StuScore;
import com.niu.crm.model.Student;
import com.niu.crm.model.User;
import com.niu.crm.service.ExamService;
import com.niu.crm.service.StudentService;

@Controller
@RequestMapping(value = "/student")
public class StudentController extends BaseController{
	@Autowired
	private StudentService studentService;
	@Autowired
	private ExamService examService;
	

	@RequestMapping(value = "/downStudents.do")
	public void downStudents(HttpServletRequest request, HttpServletResponse response,StudentExportForm form){
    	User user = this.getCurrentUser();

    	Pageable pager = null;
    	String sortFld = request.getParameter("sortFld");
    	String sortDirect = request.getParameter("sortDirect");
    	Sort.Direction direct = null;
    	if("asc".equalsIgnoreCase(sortDirect))
    		direct = Sort.Direction.ASC;
    	else
    		direct = Sort.Direction.DESC;
    		
    	
    	if(StringUtils.isNotEmpty(sortFld)){
    		sortFld = sortFld.trim().toLowerCase();
    		if(direct == null && sortFld.indexOf("exam") >=0 )
    			direct = Sort.Direction.DESC;
    		if(direct == null)
    			direct = Sort.Direction.ASC;
    		
    		pager = new PageRequest(0, 50000, direct, sortFld);
    	}
		
		if( StringUtils.isNotEmpty(form.getStuName()) )
			form.setStuName("%" + form.getStuName() + "%");	
		if( StringUtils.isNotEmpty(form.getParentName()) )
			form.setParentName("%" + form.getParentName() + "%");	
		if( StringUtils.isNotEmpty(form.getParentDanwei()) )
			form.setParentDanwei("%" + form.getParentDanwei() + "%");
    	
    	Date now = new java.util.Date();
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
    	
    	Workbook wb = studentService.exportStudents(form, pager);
    	String fileName = null;
    	if(form.getScoreTemplate() !=null && form.getScoreTemplate() )
    		fileName = "成绩导入模板.xlsx";
    	else
    		fileName = "学生信息" + sdf.format(now) + ".xlsx";
    	
    	response.setContentType("application/x-msdownload;charset=GBK");
      	
      
      	//inline 在 IE7.0.5730.13下 会造成session丢失(构造新的 session对象), google chrome 无此问题
      	//response.setHeader("Content-Disposition", "inline; filename=" + new String(fileName.getBytes(),"ISO-8859-1") );
      	java.io.OutputStream os = null;
      	try{
      		response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO-8859-1") );
      		os = response.getOutputStream();

          	wb.write( os );
          	os.flush();
          	os.close();
      	}catch(Exception e){
      		getLogger().error("", e);
      	}
      	finally{
      		if(wb !=null)
      			try{wb.close();}catch(Exception e){}
      	}
    }
	
	@RequestMapping(value = "/detail.do")
    @ResponseBody
    public ResponseObject<Student> detail(Long id){
		User user = this.getCurrentUser();
		
		Student stu = studentService.load(id);
		for(StuParent p:stu.getStuParents()){
			if(p.getDanwei() ==null)
				p.setDanwei("");
			if(p.getMobile() == null)
				p.setMobile("");
		}
		
		return new ResponseObject<>(stu);
	}
	
	@RequestMapping(value = "/list.do")
    public String list(Model model){
		User user = this.getCurrentUser();
		
		List<Exam> exams = examService.loadAll();
		model.addAttribute("exams", exams);
		return "student/list";
	}
	
	@RequestMapping(value = "/listData.do")
    @ResponseBody
    public Map<String,Object> listData(HttpServletRequest request, StudentSearchForm form, Pageable pager){
		User user = this.getCurrentUser();
		
		pager = convertPager(request, pager);
		
		Map<String,Object> map = new java.util.HashMap<String, Object>();
		List<Student> ls = null;
		int count = 0;
		
		if( StringUtils.isNotEmpty(form.getStuName()) )
			form.setStuName("%" + form.getStuName() + "%");	
		if( StringUtils.isNotEmpty(form.getParentName()) )
			form.setParentName("%" + form.getParentName() + "%");	
		if( StringUtils.isNotEmpty(form.getParentDanwei()) )
			form.setParentDanwei("%" + form.getParentDanwei() + "%");
		

		count = studentService.countStudent(form);
		if(count == 0)
			ls = new ArrayList<>();
		else
			ls = studentService.queryStudent(form, pager);

		for(Student stu:ls){
			StuScore stuScore = stu.getStuScore();
			if(stuScore == null){
				stuScore = new StuScore();
				stu.setStuScore(stuScore);
				stuScore.setStuId(stu.getId());
			}
		}
		
		
		map.put("total", count);
		map.put("rows", ls);
		
		return map;
	}
	
	@RequestMapping(value = "/saveStudent.do")
    @ResponseBody
    public ResponseObject<Boolean> saveStudent(@RequestBody Student student){
		User user = this.getCurrentUser();
		
		if(student.getId() == null){
			student.setCreatorId(user.getId());
			studentService.insert(user, student);
		}else{
			studentService.update(user, student);
		}

		return new ResponseObject<>(Boolean.TRUE);
	}
	
	@RequestMapping(value = "/saveScore.do")
    @ResponseBody
    public ResponseObject<Boolean> saveScore(Long stuId, Integer examNo, BigDecimal score){
		User user = this.getCurrentUser();
		
		studentService.updateScore(stuId, examNo, score);

		return new ResponseObject<>(Boolean.TRUE);
	}
	
	/**
	 * 导入成绩信息到数据库
	 * @return
	 */
	@RequestMapping(value = "/doImportScore.do")
    @ResponseBody
    public ResponseObject<Map<String,Object>> doImportScore(@RequestParam(value = "file") MultipartFile file, 
    		HttpServletRequest request){
		User user = this.getCurrentUser();
		Map<String, Object> map = new HashMap<>();
		
		String fileName = (file==null)?null:file.getOriginalFilename().toLowerCase();
		if (fileName ==null ) {
			map.put("msg", "请选择上传文件");
		}else if (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
			map.put("msg", "只支持excel文件格式");
		}
		else{
			Integer count = null; 
			
			try{
				count = studentService.importScore(user, file);				
			} catch (BizException e) {
				getLogger().error("", e);
				throw e;
			} catch (Exception e) {
				getLogger().error("", e);
				throw new BizException(GlobalErrorCode.INTERNAL_ERROR,
						e.getMessage());
			}
			
			map.put("count", count);
			map.put("msg", "导入成功");			
		}
		
		return new ResponseObject<>(map);
	}
	
	/**
	 * 导入学生信息页面
	 * @return
	 */
	@RequestMapping(value = "/importStudents.do")
    public String importStudents(Model model){
		User user = this.getCurrentUser();
		
		List<Exam> exams = examService.loadAll();
		model.addAttribute("exams", exams);
		return "student/import_students";
	}
	
	/**
	 * 导入学生信息
	 * @return
	 */
	@RequestMapping(value = "/doImportStudents.do")
    @ResponseBody
	public ResponseObject<Map<String,Object>> doImportStudents(@RequestParam(value = "file") MultipartFile file, 
    		HttpServletRequest request, Integer examNo){
		User user = this.getCurrentUser();
		Map<String, Object> map = new HashMap<>();
		
		String fileName = (file==null)?null:file.getOriginalFilename().toLowerCase();
		if (fileName ==null ) {
			map.put("msg", "请选择上传文件");
		}else if (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
			map.put("msg", "只支持excel文件格式");
		}
		else{
			Integer count = null; 
			
			try{
				count = studentService.importStudents(user, file);				
			} catch (BizException e) {
				getLogger().error("", e);
				throw e;
			} catch (Exception e) {
				getLogger().error("", e);
				throw new BizException(GlobalErrorCode.INTERNAL_ERROR,
						e.getMessage());
			}
			
			map.put("count", count);
			map.put("msg", "导入成功");			
		}
		
		return new ResponseObject<>(map);
	}
	
	@RequestMapping(value = "/delete.do")
    @ResponseBody
    public ResponseObject<Boolean> delete(Long id){
		User user = this.getCurrentUser();
		studentService.delete(id);
		return new ResponseObject<>(Boolean.TRUE);		
	}
}
